package com.leetroll.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.leetroll.api.mapper.UserActionMapper;
import com.leetroll.api.service.UserActionService;
import com.leetroll.common.constant.SQLConstant;
import com.leetroll.common.entity.UserAction;
import com.leetroll.common.utils.UserUtil;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class UserActionServiceImpl extends SuperServiceImpl<UserActionMapper, UserAction> implements UserActionService {

    @Override
    public UserAction getByAction(Long itemId, String action) {
        Long userId = UserUtil.getUserId();
        QueryWrapper<UserAction> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SQLConstant.USER_ID, userId);
        queryWrapper.eq(SQLConstant.ITEM_ID, itemId);
        queryWrapper.eq(SQLConstant.ACTION_ACTION, action);
        return this.getOne(queryWrapper);
    }

    @Override
    public Map<String, Long> countByItemIdAndAcion(Integer itemId) {
        QueryWrapper<UserAction> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SQLConstant.ITEM_ID, itemId);
        queryWrapper.eq(SQLConstant.ACTION_VALUE, true);
        List<UserAction> userActions = this.list(queryWrapper);
        return userActions.stream().collect(Collectors.groupingBy(UserAction::getAction, Collectors.counting()));
    }

    @Override
    public int[] listItemIdsByActionAndUser(String action, Integer pageNumber, Integer pageSize) {
        Long userId = UserUtil.getUserId();
        Page<UserAction> page = new Page<>(pageNumber, pageSize);
        QueryWrapper<UserAction> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SQLConstant.USER_ID, userId);
        queryWrapper.eq(SQLConstant.ACTION_ACTION, action);
        queryWrapper.eq(SQLConstant.ACTION_VALUE, true);
        List<UserAction> actionList = this.page(page, queryWrapper).getRecords();
       return actionList.stream().mapToInt(v -> v.getItemId().intValue()).toArray();
    }

    @Override
    public Integer countItemsByActionAndUser(String action) {
        Long userId = UserUtil.getUserId();
        QueryWrapper<UserAction> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SQLConstant.USER_ID, userId);
        queryWrapper.eq(SQLConstant.ACTION_ACTION, action);
        queryWrapper.eq(SQLConstant.ACTION_VALUE, true);
        return this.list(queryWrapper).size();
    }

    @Override
    public int countItemsByAction(Long itemId, String action) {
        QueryWrapper<UserAction> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SQLConstant.ITEM_ID, itemId);
        queryWrapper.eq(SQLConstant.ACTION_ACTION, action);
        queryWrapper.eq(SQLConstant.ACTION_VALUE, true);
        return this.list(queryWrapper).size();
    }
}
